from flask import Blueprint, jsonify, request
from models.style_template import StyleTemplate
from app import db

style_bp = Blueprint('style', __name__)

@style_bp.route('/templates', methods=['GET'])
def get_style_templates():
    """获取风格模板列表"""
    try:
        category = request.args.get('category')
        is_premium = request.args.get('is_premium')
        
        query = StyleTemplate.query.filter_by(is_active=True)
        
        if category:
            query = query.filter_by(category=category)
        
        if is_premium is not None:
            is_premium = is_premium.lower() == 'true'
            query = query.filter_by(is_premium=is_premium)
        
        templates = query.order_by(StyleTemplate.sort_order.desc(), StyleTemplate.usage_count.desc()).all()
        
        return jsonify({
            'templates': [template.to_dict() for template in templates]
        })
        
    except Exception as e:
        return jsonify({'error': f'获取模板失败: {str(e)}'}), 500

@style_bp.route('/templates/<int:template_id>', methods=['GET'])
def get_style_template(template_id):
    """获取单个风格模板详情"""
    try:
        template = StyleTemplate.query.get(template_id)
        if not template or not template.is_active:
            return jsonify({'error': '模板不存在'}), 404
        
        return jsonify({
            'template': template.to_dict()
        })
        
    except Exception as e:
        return jsonify({'error': f'获取模板失败: {str(e)}'}), 500

@style_bp.route('/categories', methods=['GET'])
def get_categories():
    """获取所有分类"""
    try:
        categories = db.session.query(StyleTemplate.category).filter_by(is_active=True).distinct().all()
        category_list = [cat[0] for cat in categories]
        
        # 分类映射（中文显示）
        category_map = {
            'portrait': '肖像证件',
            'art': '艺术风格', 
            'sci-fi': '科幻未来',
            'traditional': '传统文化',
            'cartoon': '卡通动漫',
            'professional': '职业形象',
            'fun': '趣味搞笑'
        }
        
        categories_with_names = []
        for cat in category_list:
            categories_with_names.append({
                'key': cat,
                'name': category_map.get(cat, cat),
                'count': StyleTemplate.query.filter_by(category=cat, is_active=True).count()
            })
        
        return jsonify({
            'categories': categories_with_names
        })
        
    except Exception as e:
        return jsonify({'error': f'获取分类失败: {str(e)}'}), 500